<template>
  <view class="chat-container">
    <!-- 顶部导航栏 -->
    <view class="chat-header">
      <view class="back-btn">
        <text class="icon">←</text>
      </view>
      <view class="header-title">
        <view class="main-title">智慧农场可视化认养农业开发</view>
        <view class="sub-title" @tap="toggleSessionList">
          {{ currentSession.title || '新会话' }} <text class="icon">▼</text>
        </view>
      </view>
    </view>

    <!-- 会话列表弹窗 -->
    <view class="session-popup" v-if="showSessionList">
      <view class="session-list">
        <view class="session-list-header">
          <text>会话列表</text>
          <text class="new-session" @tap="createNewSession">+ 新会话</text>
        </view>
        <scroll-view scroll-y style="max-height: 40vh;">
          <view 
            class="session-item" 
            v-for="(session, index) in sessionList" 
            :key="session.id"
            :class="{ active: currentSession.id === session.id }"
            @tap="switchSession(session)"
          >
            <text class="session-title">{{ session.title || '无标题会话' }}</text>
            <text class="session-time" v-if="!session.title || !session.title.includes('新会话')">{{ formatTime(session.updateTime) }}</text>
            <text class="delete-session" @tap.stop="deleteSession(session.id, index)">×</text>
          </view>
          <view class="no-data" v-if="sessionList.length === 0">
            暂无会话记录
          </view>
        </scroll-view>
      </view>
      <view class="session-mask" @tap="toggleSessionList"></view>
    </view>

    <!-- 聊天消息区域 -->
    <scroll-view class="message-container" id="message-panel" scroll-y @scrolltolower="scrollToBottom" scroll-with-animation>
      <view class="message-list">
        <view
          class="message-item"
          v-for="(item, index) in messageList"
          :key="index"
          :class="{ 'ai-message': item.type == 1, 'user-message': item.type == 0 }"
        >
          <!-- AI消息 -->
          <template v-if="item.type == 1">
            <view class="avatar ai-avatar">AI</view>
            <view class="message-bubble ai-bubble">
              <rich-text :nodes="formatMarkdown(item.content)" />
              <view class="loading" v-if="item.loading">
                <image src="http://121.36.197.175:19000/test/loading.gif" mode="aspectFit" />
              </view>
            </view>
          </template>
          <!-- 用户消息 -->
          <template v-else>
            <view class="message-content">
              <view class="avatar user-avatar">我</view>
              <view class="message-bubble user-bubble">
                {{ item.content }}
              </view>
            </view>
          </template>
        </view>
      </view>
    </scroll-view>

    <!-- 底部输入区域 -->
    <view class="input-container">
      <view class="input-box">
        <textarea
          class="input-field"
          auto-height
          placeholder="请输入您想的问题"
          v-model="inputContent"
          @keyup="keySend"
          :maxlength="200"
        />
      </view>
      <view class="send-button" @tap="sendMessage" :class="{ disabled: loading }">
        <text>发送</text>
      </view>
    </view>
  </view>
</template>

<script>
import { formatMarkdown } from '@/util/markdown';
import request from '@/util/request';

export default {
  data() {
    return {
      inputContent: '',
      messageList: [],
      loading: false,
      sessionList: [],
      currentSession: {
        id: '',
        title: '新会话',
        updateTime: Date.now()
      },
      showSessionList: false,
      userId: ''
    };
  },
  
  onLoad() {
    const userInfo = uni.getStorageSync('userInfo');
    if (userInfo && userInfo.userId) {
      this.userId = userInfo.userId;
      this.loadSessionList();
    } else {
      uni.showToast({ title: '请先登录', icon: 'none', duration: 2000 });
      setTimeout(() => uni.navigateTo({ url: '/pages/login/login' }), 1500);
    }
  },
  
  methods: {
    // 消息相关方法
    keySend(event) {
      if (event.ctrlKey && event.keyCode === 13) this.sendMessage();
    },
    
    sendMessage() {
      const message = this.inputContent.trim();
      if (!message || this.loading) {
        uni.showToast({ title: '请输入内容', icon: 'none' });
        return;
      }
      
      // 如果是新会话，先创建会话
      if (!this.currentSession.id) {
        this.createSession(message);
        return;
      }
      
      // 添加用户消息和AI思考中消息
      this.messageList.push({ type: 0, content: message, timestamp: Date.now() });
      this.messageList.push({ type: 1, content: 'AI 正在思考...', loading: true, timestamp: Date.now() });
      
      this.loading = true;
      this.inputContent = '';
      
      // 发送消息到后端
      request({
        url: `/ai-service/chat/sessions/${this.currentSession.id}/messages`,
        method: 'POST',
        data: { content: message }
      }).then(res => {
        const lastIndex = this.messageList.length - 1;
        
        if (lastIndex >= 0 && res?.code === 200) {
          const aiMessage = res.data.aiMessage;
          this.messageList[lastIndex].content = aiMessage?.content || '抱歉，我暂时无法回答您的问题。';
          this.messageList[lastIndex].loading = false;
          this.loadSessionList(); // 更新会话列表以刷新时间
        } else {
          this.messageList[lastIndex].content = '抱歉，处理消息失败。';
          this.messageList[lastIndex].loading = false;
        }
        
        this.loading = false;
        this.$nextTick(() => this.scrollToBottom());
      }).catch(() => {
        const lastIndex = this.messageList.length - 1;
        if (lastIndex >= 0) {
          this.messageList[lastIndex].content = '抱歉，请求失败，请稍后再试。';
          this.messageList[lastIndex].loading = false;
        }
        this.loading = false;
        uni.showToast({ title: '请求失败', icon: 'none' });
      });
    },
    
    scrollToBottom() {
      this.$nextTick(() => {
        const query = uni.createSelectorQuery().in(this);
        query.select('#message-panel').boundingClientRect((data) => {
          if (data) uni.pageScrollTo({ scrollTop: data.height, duration: 300 });
        }).exec();
      });
    },
    
    formatMarkdown(text) {
      return formatMarkdown(text);
    },
    
    // 会话管理相关方法
    toggleSessionList() {
      this.showSessionList = !this.showSessionList;
    },
    
    createNewSession() {
      request({
        url: '/ai-service/chat/sessions',
        method: 'POST',
        data: {
          userId: this.userId,
          title: '新会话'
        }
      }).then(res => {
        if (res?.code === 200 && res.data) {
          this.currentSession = res.data;
          this.currentSession.title = '新会话';
          this.messageList = [];
          this.showSessionList = false;
          this.updateSessionTitle('新会话');
          this.loadSessionList();
        } else {
          uni.showToast({ title: '创建会话失败', icon: 'none' });
        }
      }).catch(() => {
        uni.showToast({ title: '创建会话失败', icon: 'none' });
      });
    },
    
    createSession(firstMessage) {
      request({
        url: '/ai-service/chat/sessions',
        method: 'POST',
        data: {
          userId: this.userId,
          title: '新会话'
        }
      }).then(res => {
        if (res?.code === 200 && res.data) {
          this.currentSession = res.data;
          
          // 设置标题
          if (!firstMessage || firstMessage.toLowerCase().includes('新会话')) {
            this.updateSessionTitle('新会话');
          } else {
            this.updateSessionTitle(firstMessage);
          }
          
          // 发送消息
          this.sendMessage();
        } else {
          uni.showToast({ title: '创建会话失败', icon: 'none' });
        }
      }).catch(() => {
        uni.showToast({ title: '创建会话失败', icon: 'none' });
      });
    },
    
    switchSession(session) {
      this.currentSession = session;
      this.showSessionList = false;
      this.loadMessages();
    },
    
    deleteSession(sessionId, index) {
      uni.showModal({
        title: '提示',
        content: '确定要删除此会话吗？',
        success: (res) => {
          if (res.confirm) {
            request({
              url: `/ai-service/chat/sessions/${sessionId}`,
              method: 'DELETE'
            }).then(res => {
              if (res?.code === 200) {
                this.sessionList.splice(index, 1);
                
                // 如果删除的是当前会话，切换到其他会话或创建新会话
                if (this.currentSession.id === sessionId) {
                  if (this.sessionList.length > 0) {
                    this.switchSession(this.sessionList[0]);
                  } else {
                    this.createNewSession();
                  }
                }
                
                uni.showToast({ title: '删除成功', icon: 'success' });
              } else {
                uni.showToast({ title: '删除失败', icon: 'none' });
              }
            }).catch(() => {
              uni.showToast({ title: '删除失败', icon: 'none' });
            });
          }
        }
      });
    },
    
    updateSessionTitle(title) {
      if (!title || !this.currentSession.id) return;
      
      // 截取前20个字符作为标题
      const newTitle = title.length > 20 ? title.substring(0, 20) + '...' : title;
      
      request({
        url: `/ai-service/chat/sessions/${this.currentSession.id}/title`,
        method: 'PUT',
        data: { title: newTitle }
      }).then(res => {
        if (res?.code === 200 && res.data) {
          this.currentSession = res.data;
          
          // 更新会话列表中的标题
          const index = this.sessionList.findIndex(item => item.id === this.currentSession.id);
          if (index !== -1) {
            this.sessionList[index] = this.currentSession;
          }
        }
      }).catch(err => {
        console.error('更新会话标题失败', err);
      });
    },
    
    loadSessionList() {
      request({
        url: '/ai-service/chat/sessions',
        method: 'GET',
        data: { userId: this.userId }
      }).then(res => {
        if (res?.code === 200) {
          this.sessionList = res.data || [];
          
          // 如果没有当前会话或当前会话不在列表中，默认选择第一个会话或创建新会话
          if (!this.currentSession.id || !this.sessionList.find(item => item.id === this.currentSession.id)) {
            if (this.sessionList.length > 0) {
              this.currentSession = this.sessionList[0];
              this.loadMessages();
            } else {
              this.createNewSession();
            }
          }
        } else {
          this.sessionList = [];
          this.createNewSession();
        }
      }).catch(() => {
        this.sessionList = [];
        this.createNewSession();
      });
    },
    
    loadMessages() {
      if (!this.currentSession.id) return;
      
      request({
        url: `/ai-service/chat/sessions/${this.currentSession.id}/messages`,
        method: 'GET'
      }).then(res => {
        if (res?.code === 200) {
          // 转换消息格式以适应前端显示
          this.messageList = (res.data || []).map(msg => ({
            type: msg.role === 'user' ? 0 : 1,
            content: msg.content,
            timestamp: new Date(msg.createTime).getTime()
          }));
          
          this.$nextTick(() => this.scrollToBottom());
        } else {
          this.messageList = [];
        }
      }).catch(() => {
        this.messageList = [];
        uni.showToast({ title: '加载消息失败', icon: 'none' });
      });
    },
    
    formatTime(timestamp) {
      if (!timestamp) return '未知时间';
      
      // 处理时间戳
      let timeMs = timestamp;
      
      // 处理数组格式的时间戳 [year, month, day, hour, minute, second]
      if (Array.isArray(timestamp)) {
        try {
          const year = timestamp[0];
          const month = timestamp[1] - 1; // 月份从0开始
          const day = timestamp[2];
          const hour = timestamp[3] || 0;
          const minute = timestamp[4] || 0;
          const second = timestamp[5] || 0;
          
          timeMs = new Date(year, month, day, hour, minute, second).getTime();
        } catch (e) {
          return '未知时间';
        }
      } else if (typeof timestamp === 'string') {
        if (timestamp.includes('T') || timestamp.includes('-')) {
          timeMs = new Date(timestamp).getTime();
        } else {
          timeMs = parseInt(timestamp.replace(/[^\d]/g, ''));
        }
      }
      
      // 确保是毫秒级时间戳
      if (timeMs < 1000000000000 && timeMs > 0) {
        timeMs = timeMs * 1000;
      }
      
      if (isNaN(timeMs) || timeMs <= 0) return '未知时间';
      
      const date = new Date(timeMs);
      if (isNaN(date.getTime())) return '未知时间';
      
      const now = new Date();
      
      // 今天的消息只显示时间
      if (date.toDateString() === now.toDateString()) {
        return `${this.formatNumber(date.getHours())}:${this.formatNumber(date.getMinutes())}`;
      }
      
      // 昨天的消息显示"昨天"
      const yesterday = new Date(now);
      yesterday.setDate(now.getDate() - 1);
      if (date.toDateString() === yesterday.toDateString()) {
        return `昨天 ${this.formatNumber(date.getHours())}:${this.formatNumber(date.getMinutes())}`;
      }
      
      // 其他显示日期
      return `${date.getMonth() + 1}月${date.getDate()}日`;
    },
    
    formatNumber(n) {
      n = n.toString();
      return n[1] ? n : '0' + n;
    }
  }
};
</script>

<style lang="scss">
.chat-container {
  display: flex;
  flex-direction: column;
  height: 95vh;
  background-color: #f5f7fa;
  width: 100%;
  overflow: hidden;
  box-sizing: border-box;
  position: relative;
  
  // 顶部导航栏
  .chat-header {
    background: linear-gradient(to right, #1fd898, #38b4e7);
    padding: 20rpx 30rpx;
    display: flex;
    align-items: center;
    position: relative;
    z-index: 10;
    flex-shrink: 0;
    
    .back-btn {
      width: 60rpx;
      height: 60rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      color: #fff;
      font-weight: bold;
      font-size: 40rpx;
    }
    
    .header-title {
      flex: 1;
      text-align: center;
      color: #fff;
      
      .main-title {
        font-size: 45rpx;
        font-weight: 500;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
        padding: 0 20rpx;
      }
      
      .sub-title {
        font-size: 40rpx;
        opacity: 0.9;
        margin-top: 0;
        
        .icon {
          font-size: 30rpx;
          margin-left: 8rpx;
        }
      }
    }
  }
  
  // 消息区域
  .message-container {
    flex: 1;
    padding: 20rpx 30rpx;
    overflow-y: auto;
    -webkit-overflow-scrolling: touch;
    box-sizing: border-box;
    
    .message-list {
      padding-bottom: 10rpx;
      
      .message-item {
        margin-bottom: 30rpx;
        display: flex;
        
        // AI消息样式
        &.ai-message {
          align-items: flex-start;
          
          .ai-avatar {
            background: #32d296;
            color: white;
            margin-right: 15rpx;
            width: 80rpx;
            height: 80rpx;
            font-size: 36rpx;
          }
          
          .ai-bubble {
            background: #fff;
            color: #333;
            box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
            border-radius: 0 25rpx 25rpx 25rpx;
            position: relative;
            padding: 24rpx 32rpx;
            max-width: calc(85% - 80rpx);
            word-break: break-word;
            font-size: 36rpx;
            line-height: 1.5;
            
            &::before {
              content: '';
              position: absolute;
              left: -10rpx;
              top: 0;
              width: 0;
              height: 0;
              border-top: 10rpx solid #fff;
              border-left: 10rpx solid transparent;
            }
            
            .loading {
              text-align: center;
              padding: 10rpx 0;
              
              image {
                width: 40rpx;
                height: 40rpx;
                opacity: 0.7;
              }
            }
          }
        }
        
        // 用户消息样式
        &.user-message {
          justify-content: flex-end;
          
          .message-content {
            display: flex;
            flex-direction: row-reverse;
            align-items: flex-start;
            max-width: 85%;
          }
          
          .user-avatar {
            background: #007aff;
            color: white;
            margin-left: 15rpx;
            width: 80rpx;
            height: 80rpx;
            font-size: 36rpx;
          }
          
          .user-bubble {
            background: #007aff;
            color: white;
            border-radius: 25rpx 0 25rpx 25rpx;
            position: relative;
            padding: 24rpx 32rpx;
            max-width: calc(100% - 80rpx);
            text-align: left;
            word-break: break-word;
            font-size: 36rpx;
            line-height: 1.5;
            
            &::before {
              content: '';
              position: absolute;
              right: -10rpx;
              top: 0;
              width: 0;
              height: 0;
              border-top: 10rpx solid #007aff;
              border-right: 10rpx solid transparent;
            }
          }
        }
        
        .avatar {
          border-radius: 50%;
          display: flex;
          align-items: center;
          justify-content: center;
          font-weight: 500;
          flex-shrink: 0;
        }
      }
    }
  }
  
  // 底部输入区域
  .input-container {
    display: flex;
    padding: 24rpx 30rpx;
    background: #fff;
    border-top: 2rpx solid #eaeaea;
    align-items: center;
    position: relative;
    z-index: 10;
    box-sizing: border-box;
    flex-shrink: 0;
    
    .input-box {
      flex: 1;
      background: #f5f5f5;
      border-radius: 40rpx;
      padding: 16rpx 24rpx;
      margin-right: 15rpx;
      
      .input-field {
        width: 100%;
        min-height: 60rpx;
        max-height: 180rpx;
        font-size: 34rpx;
        line-height: 1.4;
        background: transparent;
        border: none;
        box-sizing: border-box;
        padding: 8rpx 12rpx;
        
        &:focus {
          outline: none;
        }
      }
    }
    
    .send-button {
      width: 120rpx;
      height: 80rpx;
      background: linear-gradient(to right, #1fd898, #38b4e7);
      border-radius: 40rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      color: white;
      font-size: 34rpx;
      
      &.disabled {
        opacity: 0.6;
      }
      
      &:active {
        opacity: 0.8;
      }
    }
  }
  
  // 会话列表弹窗样式
  .session-popup {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    z-index: 999;
    
    .session-mask {
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      background: rgba(0, 0, 0, 0.5);
    }
    
    .session-list {
      position: absolute;
      top: 120rpx;
      left: 50%;
      transform: translateX(-50%);
      width: 90%;
      background: #fff;
      border-radius: 24rpx;
      box-shadow: 0 10rpx 30rpx rgba(0, 0, 0, 0.2);
      z-index: 1000;
      overflow: hidden;
      
      .session-list-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 24rpx 30rpx;
        border-bottom: 2rpx solid #eaeaea;
        
        text {
          font-size: 36rpx;
          font-weight: 500;
        }
        
        .new-session {
          color: #1fd898;
          font-size: 32rpx;
        }
      }
      
      .session-item {
        padding: 24rpx 30rpx;
        border-bottom: 2rpx solid #f0f0f0;
        display: flex;
        align-items: center;
        position: relative;
        
        &.active {
          background: #f0f7ff;
        }
        
        .session-title {
          flex: 1;
          font-size: 32rpx;
          white-space: nowrap;
          overflow: hidden;
          text-overflow: ellipsis;
        }
        
        .session-time {
          font-size: 28rpx;
          color: #999;
          margin-left: 16rpx;
        }
        
        .delete-session {
          margin-left: 16rpx;
          color: #ff3b30;
          font-size: 36rpx;
          width: 40rpx;
          height: 40rpx;
          line-height: 40rpx;
          text-align: center;
        }
      }
    }
  }
}

.no-data {
  text-align: center;
  color: #999;
  font-size: 32rpx;
  padding: 30rpx 0;
}

/* 媒体查询，适配不同屏幕尺寸 */
@media screen and (max-width: 320px) {
  .chat-container {
    .message-container .message-list .message-item {
      .ai-bubble, .user-bubble {
        font-size: 16px;
        padding: 12px 16px;
      }
      
      .avatar {
        width: 36px;
        height: 36px;
        font-size: 14px;
      }
    }
    
    .input-container {
      padding: 10px 12px;
      
      .send-button {
        width: 60px;
        height: 40px;
        font-size: 16px;
      }
    }
  }
}

@media screen and (min-width: 768px) {
  .chat-container {
    max-width: 750px;
    margin: 0 auto;
    border-left: 1px solid #eaeaea;
    border-right: 1px solid #eaeaea;
    
    .message-container .message-list .message-item {
      .ai-bubble, .user-bubble {
        max-width: 70%;
      }
    }
  }
}
</style>
